package com.mayikt.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 手写一个JWT
 *
 * @author zhangkaiqi
 * @date 2021/8/9 15:00:09
 */
public class JWTTest {
    /**
     * 盐值
     */
    private static final String SIGN_KEY = "kevin";

    public static void main(String[] args) throws UnsupportedEncodingException {
        //手写JWT 封装头载体签名
        JSONObject header = new JSONObject();
        header.put("alg", "HS256");
        JSONObject payload = new JSONObject();
        payload.put("phone", "12345678910");
        //签名    实际上就是MD5
        String headerEncoder = Base64.getEncoder().encodeToString(header.toJSONString().getBytes());
        String payloadString = payload.toJSONString();
        String payloadEncoder = Base64.getEncoder().encodeToString(payloadString.getBytes());
        //sign签名值
        String sign = DigestUtils.md5Hex(payloadString + SIGN_KEY);
        String jwt = headerEncoder + "." + payloadEncoder + "." + sign;
        System.out.println(jwt);

        //解密
        String payLoad = jwt.split("\\.")[1];
        String payLoadDecoder = new String(Base64.getDecoder().decode(payLoad), StandardCharsets.UTF_8);
        String newSign = DigestUtils.md5Hex(payLoadDecoder + SIGN_KEY);
        System.out.println(newSign.equals(jwt.split("\\.")[2]));
    }
}
